package com.kits.store.ui.kits

import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
import kotlin.jvm.Throws


/**
 * 1. 如果 API < 29 的情况下，可以直接访问文件夹路径
 * 2. 如果 API = 29 且 requestLegacyExternalStorage="true" 可以直接访问文件夹路径
 * 3. 如果 API = 29 且 requestLegacyExternalStorage="false" 使用MediaStore 访问 公共文件夹
 * 4. 如果 API > 29 使用MediaStore 访问 公共文件夹
 * 存储图片资源文件：
 * 不设置路径：默认为 Pictures。设置路径只是 DCIM 或者 Pictures（及其子文件夹）
 * 保存的文件可以是非照片资源文件
 */
class ImageStorage {

    lateinit var gInsertUri: Uri
    lateinit var gMediaId: String
    /**
     * 1. 标准路径，标准文件(具体操作分为增删改查)
     */
    fun standImageDirFile(context: Context){
        // 增
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val contentValues = ContentValues()
            println("设置相对路径")
            //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/cxm")
            //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/Screenshots/")
            // allowed directories are [DCIM, Pictures]
            //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Download/Screenshots/")
            //addFile(context,contentValues)
        }else{
            //addFile(context,ContentValues())
        }
        queryFile(context,"SimpleTest.jpg")
//        // 改
//        println("修改数据===")
//        //updateFile(context,ContentValues())
//        update1(context)
//        // 查
//        queryFile(context,"newPicture.jpg")
        // 删
       // delete(context)
    }
    @RequiresApi(Build.VERSION_CODES.R)
    private fun addFile(context: Context, contentValues: ContentValues){
        contentValues.put(MediaStore.Images.Media.DESCRIPTION, "This is an image")
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "SimpleTest.jpg")
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg")
        contentValues.put(MediaStore.Images.Media.TITLE, "SimpleTest.jpg")
//        contentValues.put(MediaStore.Images.Media.WRITER,"chenxumeng")
        val insertUri = context?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues)
        println("insertUri == $insertUri")

        insertUri?. let{
            gInsertUri = insertUri
            context?.contentResolver?.openOutputStream(it)
        }?.let {
            val bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888)
            val tmpCanvas = Canvas()
            tmpCanvas.setBitmap(bitmap)
            tmpCanvas.drawColor(Color.GREEN)
            tmpCanvas.save()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
            it.close()
            bitmap.recycle()
        }
    }

    /**
     *
     *  query(@RequiresPermission.Read @NonNull Uri uri,
        @Nullable String[] projection, @Nullable String selection,
        @Nullable String[] selectionArgs, @Nullable String sortOrder)
        c = mContentResolver.query(MediaStore.Files.getContentUri("external"), null,
        MediaStore.Video.Media.BUCKET_DISPLAY_NAME+"=?", "ScreenRecord", null);
     */
    private fun queryFile(context: Context,name:String){
        val queryCursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,
            MediaStore.Images.Media.DISPLAY_NAME+"=?", arrayOf(name),null)
        println("queryUri == $queryCursor")
        queryCursor?.let {
            println("number == ${it.count}")
            if (it.count == 0){
                return
            }
            println("columnCount == ${it.columnCount}")

            it.moveToFirst()
            do {
                for (index in 0 until it.columnCount){
                    println("${it.getColumnName(index)} == ${it.getString(index)}")
                }
                gMediaId = it.getString(it.getColumnIndex(MediaStore.Images.Media._ID))

            } while (it.moveToNext())
        }
        // 尝试一下修改文件
        val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,gMediaId.toLong())
        //changeByBitmap(context,uri)
        val inputStream = inputStream(context,uri)
        val bitmap = BitmapFactory.decodeStream(inputStream)
        val tmpCanvas = Canvas()
        tmpCanvas.setBitmap(bitmap)
        tmpCanvas.drawColor(Color.RED)
        tmpCanvas.save()
    }
    @Throws(FileNotFoundException::class)
    fun inputStream(context: Context,uri:Uri):InputStream?{
        return context.contentResolver?.openInputStream(uri)
    }

    @Throws(FileNotFoundException::class)
    fun outputStream(context: Context,uri:Uri):OutputStream?{
        return context.contentResolver?.openOutputStream(uri)
    }
    fun changeByBitmap(context: Context,uri:Uri){
        //val inputStream = context.contentResolver?.openInputStream(uri)
        val outputStream = context.contentResolver.openOutputStream(uri)
        //val bitmap = BitmapFactory.decodeStream(inputStream)
        val bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888)
        val tmpCanvas = Canvas()
        tmpCanvas.setBitmap(bitmap)
        tmpCanvas.drawColor(Color.RED)
        tmpCanvas.save()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        //inputStream?.close()
        outputStream?.close()
    }

    /**
     * 修改基本信息
     *
     * switch (match) {
     *case AUDIO_MEDIA_ID:
    case VIDEO_MEDIA_ID:
    case IMAGES_MEDIA_ID:
    case DOWNLOADS_ID:
    break;
    default:
    throw new IllegalArgumentException("Movement of " + uri
    + " which isn't part of well-defined collection not allowed");
    }
     这个接口具体有什么用 从官方上看，只有在大文件更新的时候才使用update
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    private fun updateFile(context: Context, contentValues: ContentValues) {
        contentValues.apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "SimpleTest.jpg")
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpg")
            put(MediaStore.Images.Media.IS_PENDING, 1) // 独占
        }
        val insertUri = context?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues)
        println("insertUri == $insertUri")
        insertUri?. let{
            context?.contentResolver?.openOutputStream(it)
        }?.let {
            val bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888)
            val tmpCanvas = Canvas()
            tmpCanvas.setBitmap(bitmap)
            tmpCanvas.drawColor(Color.GREEN)
            tmpCanvas.save()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
            it.close()
            bitmap.recycle()
            contentValues.clear()
            contentValues.put(MediaStore.Audio.Media.IS_PENDING, 0)
            context?.contentResolver?.update(insertUri, contentValues, null, null)
        }

    }


    private fun update1(context: Context){
        val resolver = context.contentResolver
        val selection = "${MediaStore.Audio.Media._ID} = ?"
        val selectionArgs = arrayOf(gMediaId)
        val updatedSongDetails = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "newPicture.jpg")
        }

        val numSongsUpdated = resolver.update(
            gInsertUri,
            updatedSongDetails,
            selection,
            selectionArgs)

        println("测试一下是否更新了 $numSongsUpdated")
    }

    private fun delete(context: Context){
        val ret = context?.contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.Media.DISPLAY_NAME+"=?", arrayOf("SimpleTest.png"))
        println("ret == $ret")
    }

}